package com.mp.approvalreq.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mp.approvalreq.entity.Email;
import com.mp.approvalreq.service.SubmitRequestServicePrx;
import com.mp.approvalreq.util.ServiceUtils;
import com.mp.approvalreq.util.ValidateUtil;
import com.mp.user.entity.User;
import com.plusmoney.exception.RpcServerLogicalException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 保存导出审批的邮箱
 */
@WebServlet("/saveExportEmail")
public class SaveExportEmail extends AbstractServlet {

    private static final Logger logger = LoggerFactory.getLogger(SaveExportEmail.class);

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
        try {
            User user = getReqUser(req);
            Email email = getEmail(req);

            check(email);

            SubmitRequestServicePrx submitRequestServicePrx = ServiceUtils.getSubmitRequestServicePrx();
            submitRequestServicePrx.saveExportEmail(email, user);

            returnResult(resp);
        } catch (Throwable e) {
            logger.error(e.getMessage(), e);
            onThrowable(req, resp, e);
        }
    }

    private void returnResult(HttpServletResponse resp) throws IOException {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("result", "0");
        jsonObject.put("res_info", "保存成功");

        logger.info(JSON.toJSONString(jsonObject));

        printJson(resp, jsonObject.toJSONString());
    }

    private Email getEmail(HttpServletRequest req) throws IOException {
        String reqBody = getContent(req);
        logger.info("json参数 {}", reqBody);

        Email email;
        try {
            email = JSONObject.parseObject(reqBody, Email.class);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RpcServerLogicalException(1, "审批内容提交失败，请稍候再试");
        }

        return email;
    }

    private void check(Email email) {
        if (email.getEmail() == null || email.getEmail().equals("")) {
            throw new RpcServerLogicalException(1, "请输入邮箱");
        }

        for (String emailStr : email.getEmail().split(",")) {
            if (!ValidateUtil.isEmail(emailStr)) {
                throw new RpcServerLogicalException(1, "邮箱格式错误,请核对后提交");
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
        doPost(req, resp);
    }

}
